package org.example.test;

import org.example.domain.Author;
import org.example.domain.Book;
import org.junit.Test;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;

/**
 * @author liuga
 * @date 2022/10/12 10:11
 * Description:
 */
public class OptionalTest03 {

    public static Author getAuthor() {
        Author author = new Author(1L, "蒙多", 33, "一个从菜刀中明悟哲理的祖安人", null);
        return null;
    }

    public static Optional<Author> getAuthorOptional() {
        Author author = new Author(1L, "蒙多", 33, "一个从菜刀中明悟哲理的祖安人", null);
        List<Book> books1 = new ArrayList<>();

        books1.add(new Book(1L, "刀的两侧是光明与黑暗", "哲学,爱情", 88, "用一把刀划分了爱恨"));
        books1.add(new Book(2L, "一个人不能死在同一把刀下", "个人成长,爱情", 99, "讲述如何从失败中明悟真理"));
        author.setBooks(books1);
        return Optional.ofNullable(author);
    }

    public static void main(String[] args) {
        //Author author = getAuthor();
      /*  if (author != null) {
            System.out.println(author.getName());
        }*/
        //返回一个描述指定值的Optional ，如果非 null ，否则返回一个空Optional
        //Optional<Author> authorOptional = Optional.ofNullable(author);
        Optional<Author> authorOptional = getAuthorOptional();
        authorOptional.ifPresent(System.out::println);
    }

    @Test
    public void test() {
        Optional<Author> authorOptional = getAuthorOptional();
        // Author author1 = authorOptional.orElseGet(() -> new Author(1L, "蒙多", 33, "一个从菜刀中明悟哲理的祖安人", null));
        // System.out.println(author1);

//        try {
//            authorOptional.orElseThrow(() -> new Throwable("值不存在"));
//        } catch (Throwable e) {
//            throw new RuntimeException(e);
//        }

        authorOptional.filter(author -> author.getAge() > 10).ifPresent(System.out::println);
    }

    @Test
    public void test2() {
        Optional<Author> authorOptional = getAuthorOptional();
        authorOptional.map(Author::getBooks).ifPresent(System.out::println);
    }
}
